package com.dragon.www.haier.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Environment;

import com.dragon.www.haier.SHApplication;
import com.dragon.www.haier.activity.MainActivity;
import com.dragon.www.haier.entity.Device;
import com.dragon.www.haier.entity.Room;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * 数据库操作类
 */
public class DataHelper extends SQLiteOpenHelper {

    // 数据库名称
    private static String DB_NAME = "smarthome";
    public final static String DB_DIR="/data/data/com.dragon.www.smarthome/databases";
    // 数据库版本
    private static int DB_VERSION = 1;
    public SQLiteDatabase db;
    private static DataHelper dataHelper = null;



    /**
     * 第一次实例化时调用
     *
     * @return
     */
    public synchronized static DataHelper getInstance() {
        if (dataHelper == null) {
            dataHelper = new DataHelper(SHApplication.getContext());
        }
        return dataHelper;
    }

    /**
     * @param context context
     * @brief 构造函数
     */
    public DataHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
        db = getWritableDatabase();
        //db = openDatabase(context);
    }


    public final static String DATABASE_PATH = Environment.getExternalStorageDirectory().getAbsolutePath()+ "/smart";
    public final static String DATABASE_FILENAME = "smarthome";
//    /**
//     * 加载外部DB文件
//     *
//     * @param context
//     * @return
//     */
//    public SQLiteDatabase openDatabase(Context context) {
//        try {
//            String databaseFilename = DATABASE_PATH + "/" + DATABASE_FILENAME;
//            File pathDir = new File(DATABASE_PATH);
//            if (!pathDir.exists()) pathDir.mkdir();
//            if (!(new File(databaseFilename)).exists())
//            {
//                InputStream is = context.getResources().openRawResource(
//                        R.raw.smarthome);
//                FileOutputStream fos = new FileOutputStream(databaseFilename);
//                byte[] buffer = new byte[8192];
//                int count = 0;
//                while ((count = is.read(buffer)) > 0)
//                {
//                    fos.write(buffer, 0, count);
//                }
//
//                fos.close();
//                is.close();
//            }
//
//            SQLiteDatabase database = SQLiteDatabase.openOrCreateDatabase(
//                    databaseFilename, null);
//            return database;
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return null;
//    }

    /**
     * 当第一次创建数据库的时候，调用该方法
     */
    @Override
    public void onCreate(SQLiteDatabase db) {
        // 创建房间表
        db.execSQL("create table " + SqliteHelper.TB_ROOM
                + " (" + SqliteHelper.Field_ROOMID + " integer primary key,"
                + SqliteHelper.Field_ROOMNAME + " varchar(100),"
                + SqliteHelper.Field_DEVICEID + " integer,"
                + SqliteHelper.Field_ROOMDESCRIPTION + " varchar(100),"
                + SqliteHelper.Field_IMGPATH + " varchar(200),"
                + SqliteHelper.Field_CREATE_TIME + " long"
                + ")");

        // 创建设备表
        db.execSQL("create table " + SqliteHelper.TB_DEVICE
                + " (" + SqliteHelper.Field_ID + " integer,"
                + SqliteHelper.Field_DEVICEID + " integer,"
                + SqliteHelper.Field_TYPE + " varchar(20),"
                + SqliteHelper.Field_ROOMID + " integer not null,"
                + SqliteHelper.Field_DEVICENAME + " varchar(100),"
                + SqliteHelper.Field_DESCRIPTION + " varchar(100),"
                + SqliteHelper.Field_COMPANY + " varchar(100),"
                + SqliteHelper.Field_STATUS + " blob,"
                + SqliteHelper.Field_IP + " varchar(15),"
                + SqliteHelper.Field_TEMPLATENAME + " varchar(100),"
                + SqliteHelper.Field_CREATE_TIME + " long,"
                + " primary key(" + SqliteHelper.Field_DEVICEID + "," + SqliteHelper.Field_TYPE + "," + SqliteHelper.Field_ROOMID + ") "
                + "FOREIGN KEY (" + SqliteHelper.Field_ROOMID + ") REFERENCES " + SqliteHelper.TB_ROOM + " (" + SqliteHelper.Field_ROOMID + ")"
                + ")");
    }

    /**
     * 当更新数据库的时候执行该方法
     */
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        //输出更新数据库的日志信息

    }

    public void open() {
        db = getWritableDatabase();
    }

    /**
     * 关闭数据库
     *
     * @return 无
     */
    public void close() {
        db.close();
    }

    public String addRoom(String roomName, String roomDescripton, String roomImgPath, long createTime, String deviceName, String deviceId, String ip,String template) {
        String msg;
        db.beginTransaction();
        msg = DataHelper.getInstance().insertRoom(roomName, roomDescripton, roomImgPath, createTime);
        if (msg.contains("失败")) {
            db.endTransaction(); //处理完成
            return "添加失败";
        }
        int roomid = DataHelper.getInstance().getMaxRoomId();
        int id = getMaxId() + 1;
        msg = DataHelper.getInstance().insertDevice(id, roomid, MainActivity.TYPE_CONTROLLER, deviceName, deviceId, ip, template);
        if (msg.contains("失败")) {
            db.endTransaction(); //处理完成
            return "添加失败";
        }

        msg = DataHelper.getInstance().updateRoom(roomid, id);
        if (msg.contains("失败")) {
            db.endTransaction(); //处理完成
            return "添加失败";
        }
        db.setTransactionSuccessful();
        db.endTransaction();
        return "添加成功";
    }

    /**
     * 添加房间
     */
    public String insertRoom(String roomName, String roomDescripton, String roomImgPath, long createTime) {
        try {
            db.execSQL(
                    "INSERT INTO "
                            + SqliteHelper.TB_ROOM
                            + "(" + SqliteHelper.Field_ROOMNAME + ","  + SqliteHelper.Field_ROOMDESCRIPTION + "," + SqliteHelper.Field_IMGPATH + "," + SqliteHelper.Field_CREATE_TIME + ") VALUES (?,?,?,?)",
                    new Object[]{roomName, roomDescripton, roomImgPath, createTime});
            return "添加成功!";
        } catch (Exception e) {
            e.printStackTrace();
            return "添加成功!";
        }
    }

    /**
     * 获得最大rommid
     * @return
     */
    public int getMaxRoomId() {
        Cursor cursor = db.rawQuery("select max(" + SqliteHelper.Field_ROOMID + ")"
                + " from " + SqliteHelper.TB_ROOM , null);
        cursor.moveToFirst();

        int roomId = -1;
        while (!cursor.isAfterLast()) {
            roomId = cursor.getInt(0);
            cursor.moveToNext();
        }
        cursor.close();
        return roomId;
    }

    /**
     * 修改房间信息
     */
    public String updateRoom(int id, String roomName, String roomDescription) {
        String sql = "UPDATE "
                + SqliteHelper.TB_ROOM
                + " SET " + SqliteHelper.Field_ROOMNAME + "='" + roomName + "'," + SqliteHelper.Field_ROOMDESCRIPTION + "='" + roomDescription + "'"
                + " WHERE " + SqliteHelper.Field_ROOMID + "=" + id;
        try {
            db.execSQL(sql);
            return "更新成功!";
        } catch (Exception e) {
            e.printStackTrace();
            return "更新失败!";
        }
    }

    /**
     * 修改房间背景
     */
    public String updateRoom(int roomid, String imgPath) {
        String sql = "UPDATE "
                + SqliteHelper.TB_ROOM
                + " SET " + SqliteHelper.Field_IMGPATH + "='" + imgPath + "'"
                + " WHERE " + SqliteHelper.Field_ROOMID + "=" + roomid;
        try {
            db.execSQL(sql);
            return "更新成功!";
        } catch (Exception e) {
            e.printStackTrace();
            return "更新失败!";
        }
    }

    /**
     * 修改房间背景
     */
    public String updateRoom(int roomid, int deviceId) {
        String sql = "UPDATE "
                + SqliteHelper.TB_ROOM
                + " SET " + SqliteHelper.Field_DEVICEID + "='" + deviceId + "'"
                + " WHERE " + SqliteHelper.Field_ROOMID + "=" + roomid;
        try {
            db.execSQL(sql);
            return "更新成功!";
        } catch (Exception e) {
            e.printStackTrace();
            return "更新失败!";
        }
    }

    /**
     * 删除房间
     */
    public String deleteRoom(int id) {
        try {
            db.execSQL(
                    "DELETE FROM "
                            + SqliteHelper.TB_ROOM
                            + " WHERE " + SqliteHelper.Field_ROOMID + "=" + id);
            return "删除成功!";
        } catch (Exception e) {
            e.printStackTrace();
            return "该房间有绑定设备,请先删除设备后重试!";
        }
    }

    /**
     * 查询所有房间
     * @return
     */
    public List<Room> getRooms() {
        List<Room> rooms = new ArrayList<>();
        Cursor cursor = db.rawQuery("select " + SqliteHelper.Field_ROOMID
                + ","   + SqliteHelper.Field_ROOMNAME
                + ","   + SqliteHelper.Field_ROOMDESCRIPTION
                + ","   + SqliteHelper.Field_IMGPATH
                + ","   + SqliteHelper.Field_DEVICEID
                + " from " + SqliteHelper.TB_ROOM , null);
        cursor.moveToFirst();

        while (!cursor.isAfterLast()) {
            Room room = new Room();
            int roomId = cursor.getInt(0);
            String roomName = cursor.getString(1);
            String roomDescription = cursor.getString(2);
            String imgPath = cursor.getString(3);
            int deviceId = cursor.getInt(4);
            room.setRoomid(roomId);
            room.setRoomName(roomName);
            room.setRoomDesciption(roomDescription);
            room.setImgPath(imgPath);
            room.setDeviceId(deviceId);
            rooms.add(room);
            cursor.moveToNext();
        }
        cursor.close();
        return rooms;
    }

    /**
     * 查询某一房间
     * @return
     */
    public Room getRoom(int roomid) {
        Room room = new Room();
        Cursor cursor = db.rawQuery("select " + SqliteHelper.Field_ROOMID
                + ","   + SqliteHelper.Field_ROOMNAME
                + ","   + SqliteHelper.Field_ROOMDESCRIPTION
                + ","   + SqliteHelper.Field_IMGPATH
                + ","   + SqliteHelper.Field_DEVICEID
                + " from " + SqliteHelper.TB_ROOM + " WHERE " + SqliteHelper.Field_ROOMID + "=" + roomid, null);
        cursor.moveToFirst();

        while (!cursor.isAfterLast()) {
            int roomId = cursor.getInt(0);
            String roomName = cursor.getString(1);
            String roomDescription = cursor.getString(2);
            String imgPath = cursor.getString(3);
            int deviceId = cursor.getInt(4);
            room.setRoomid(roomId);
            room.setRoomName(roomName);
            room.setRoomDesciption(roomDescription);
            room.setImgPath(imgPath);
            room.setDeviceId(deviceId);
            cursor.moveToNext();
        }
        cursor.close();
        return room;
    }

    /**
     * 添加设备
     */
    public String insertDevice(int id, int roomId, String type, String deviceName, String deviceId, String ip,String template) {
        try {
            db.execSQL(
                    "INSERT INTO "
                            + SqliteHelper.TB_DEVICE
                            + "(" + SqliteHelper.Field_ID + "," + SqliteHelper.Field_ROOMID + "," + SqliteHelper.Field_TYPE + "," + SqliteHelper.Field_DEVICENAME + "," + SqliteHelper.Field_DEVICEID + "," + SqliteHelper.Field_IP + "," + SqliteHelper.Field_TEMPLATENAME + "," + SqliteHelper.Field_CREATE_TIME + ") VALUES (?,?,?,?,?,?,?,?)",
                    new Object[]{id, roomId, type, deviceName, deviceId, ip,template,Calendar.getInstance().getTimeInMillis()});
            return "添加成功!";
        } catch (Exception e) {
            e.printStackTrace();
            return "添加失败!";
        }
    }

    /**
     * 修改设备
     */
    public String updateDevice(int roomId, int oldDeviceId, String deviceName, int newDeviceId, String type, String ip,String template) {
        String sql = "UPDATE "
                + SqliteHelper.TB_DEVICE
                + " SET " + SqliteHelper.Field_DEVICENAME + "='" + deviceName + "'"
                + "," + SqliteHelper.Field_DEVICEID + "=" + newDeviceId
                + "," + SqliteHelper.Field_IP + "='" + ip + "'"
                + "," + SqliteHelper.Field_TEMPLATENAME + "='" + template + "'"
                + " WHERE " + SqliteHelper.Field_DEVICEID + "=" + oldDeviceId
                + " AND " + SqliteHelper.Field_TYPE + "=" + type
                + " AND " + SqliteHelper.Field_ROOMID + "=" + roomId;
        try {
            db.execSQL(sql);
            return "更新成功!";
        } catch (Exception e) {
            e.printStackTrace();
            return "更新失败!";
        }
    }

    /**
     * 修改设备状态
     */
    public String updateDeviceStatus(int id, byte[] status) {
        //将字节数组保存到数据库中
        ContentValues cv=new ContentValues();
        cv.put(SqliteHelper.Field_STATUS, status);
        String[] args = {String.valueOf(id)};
        int isSuccess = db.update(SqliteHelper.TB_DEVICE, cv, SqliteHelper.Field_ID + "=?", args);

        if (isSuccess == 1) {
            return "更新成功!";
        } else {
            return "更新失败!";
        }
    }

    /**
     * 删除设备
     */
    public String deleteDevice(int roomid,int deviceId,String type) {
        try {
            db.execSQL(
                    "DELETE FROM "
                            + SqliteHelper.TB_DEVICE
                            + " WHERE " + SqliteHelper.Field_ROOMID + "=" + roomid
                            + " AND " + SqliteHelper.Field_DEVICEID + "=" + deviceId
                            + " AND " + SqliteHelper.Field_TYPE + "=" + type);
            return "删除成功!";
        } catch (Exception e) {
            e.printStackTrace();
            return "删除失败!";
        }
    }

    /**
     * 删除设备
     */
    public String deleteDevice(int roomid) {
        try {
            db.execSQL(
                    "DELETE FROM "
                            + SqliteHelper.TB_DEVICE
                            + " WHERE " + SqliteHelper.Field_ROOMID + "=" + roomid);
            return "删除成功!";
        } catch (Exception e) {
            e.printStackTrace();
            return "删除失败!";
        }
    }

    /**
     * 获得房间下的盒子信息
     * @return
     */
    public List<Device> getControlDevice() {
        List<Device> devices = new ArrayList<>();
        Cursor cursor = db.rawQuery("select "+ SqliteHelper.TB_DEVICE + "." + SqliteHelper.Field_ID
                + "," + SqliteHelper.TB_DEVICE + "." + SqliteHelper.Field_DEVICEID
                + "," + SqliteHelper.TB_DEVICE + "." +  SqliteHelper.Field_DEVICENAME
                + "," + SqliteHelper.TB_DEVICE + "." + SqliteHelper.Field_DESCRIPTION
                + "," + SqliteHelper.TB_DEVICE + "." + SqliteHelper.Field_COMPANY
                + "," + SqliteHelper.TB_DEVICE + "." + SqliteHelper.Field_TYPE
                + "," + SqliteHelper.TB_DEVICE + "." + SqliteHelper.Field_IP
                + "," + SqliteHelper.TB_DEVICE + "." + SqliteHelper.Field_STATUS
                + "," + SqliteHelper.TB_DEVICE + "." + SqliteHelper.Field_ROOMID
                + "," + SqliteHelper.TB_DEVICE+ "." + SqliteHelper.Field_TEMPLATENAME
                + " from " + SqliteHelper.TB_DEVICE
                + " where " + SqliteHelper.TB_DEVICE + "." + SqliteHelper.Field_TYPE + "=" + MainActivity.TYPE_CONTROLLER
                , null);
        cursor.moveToFirst();

        while (!cursor.isAfterLast()) {
            Device device = new Device();
            int id = cursor.getInt(cursor.getColumnIndex(SqliteHelper.Field_ID));
            int deviceId = cursor.getInt(cursor.getColumnIndex(SqliteHelper.Field_DEVICEID));
            String deviceName = cursor.getString(cursor.getColumnIndex(SqliteHelper.Field_DEVICENAME));
            String description = cursor.getString(cursor.getColumnIndex(SqliteHelper.Field_DESCRIPTION));
            String company = cursor.getString(cursor.getColumnIndex(SqliteHelper.Field_COMPANY));
            String type = cursor.getString(cursor.getColumnIndex(SqliteHelper.Field_TYPE));
            String ip = cursor.getString(cursor.getColumnIndex(SqliteHelper.Field_IP));
            byte[] status = cursor.getBlob(cursor.getColumnIndex(SqliteHelper.Field_STATUS));
            int roomid = cursor.getInt(cursor.getColumnIndex(SqliteHelper.Field_ROOMID));
            String template = cursor.getString(cursor.getColumnIndex(SqliteHelper.Field_TEMPLATENAME));
            device.setId(id);
            device.setRoomid(roomid);
            device.setDeviceId(deviceId);
            device.setDeviceName(deviceName);
            device.setDescription(description);
            device.setCompany(company);
            device.setType(type);
            device.setIp(ip);
            device.setTemplateName(template);
            device.setStatus(status);
            devices.add(device);
            cursor.moveToNext();
        }
        cursor.close();
        return devices;
    }

    /**
     * 某房间下所有设备
     * @return
     */
    public List<Device> getDevices(int roomid, String type) {
        List<Device> devices = new ArrayList<>();
        Cursor cursor = db.rawQuery("select "
                + SqliteHelper.Field_ID
                + ","   + SqliteHelper.Field_DEVICEID
                + ","   + SqliteHelper.Field_DEVICENAME
                + ","   + SqliteHelper.Field_DESCRIPTION
                + ","   + SqliteHelper.Field_COMPANY
                + ","   + SqliteHelper.Field_TYPE
                + ","   + SqliteHelper.Field_IP
                + ","   + SqliteHelper.Field_STATUS
                + ","   + SqliteHelper.Field_TEMPLATENAME
                + " from " + SqliteHelper.TB_DEVICE
                + " where " + SqliteHelper.Field_ROOMID + "=" + roomid
                + " and " + SqliteHelper.Field_TYPE + "=" + type
                , null);
        cursor.moveToFirst();

        while (!cursor.isAfterLast()) {
            Device device = new Device();
            int id = cursor.getInt(cursor.getColumnIndex(SqliteHelper.Field_ID));
            int deviceId = cursor.getInt(cursor.getColumnIndex(SqliteHelper.Field_DEVICEID));
            String deviceName = cursor.getString(cursor.getColumnIndex(SqliteHelper.Field_DEVICENAME));
            String description = cursor.getString(cursor.getColumnIndex(SqliteHelper.Field_DESCRIPTION));
            String company = cursor.getString(cursor.getColumnIndex(SqliteHelper.Field_COMPANY));
            String ip = cursor.getString(cursor.getColumnIndex(SqliteHelper.Field_IP));
            byte[] status = cursor.getBlob(cursor.getColumnIndex(SqliteHelper.Field_STATUS));
            String template = cursor.getString(cursor.getColumnIndex(SqliteHelper.Field_TEMPLATENAME));
            device.setId(id);
            device.setRoomid(roomid);
            device.setDeviceId(deviceId);
            device.setDeviceName(deviceName);
            device.setDescription(description);
            device.setCompany(company);
            device.setType(type);
            device.setIp(ip);
            device.setTemplateName(template);
            device.setStatus(status);
            devices.add(device);
            cursor.moveToNext();
        }
        cursor.close();
        return devices;
    }

    /**
     * 某房间下的盒子
     * @return
     */
    public Device getDevice(int roomid, String type) {
        Cursor cursor = db.rawQuery("select "
                + SqliteHelper.Field_ID
                + ","   + SqliteHelper.Field_DEVICEID
                + ","   + SqliteHelper.Field_DEVICENAME
                + ","   + SqliteHelper.Field_DESCRIPTION
                + ","   + SqliteHelper.Field_COMPANY
                + ","   + SqliteHelper.Field_TYPE
                + ","   + SqliteHelper.Field_IP
                + ","   + SqliteHelper.Field_STATUS
                + ","   + SqliteHelper.Field_TEMPLATENAME
                + " from " + SqliteHelper.TB_DEVICE
                + " where " + SqliteHelper.Field_ROOMID + "=" + roomid
                + " and " + SqliteHelper.Field_TYPE + "=" + type
                , null);
        cursor.moveToFirst();

        while (!cursor.isAfterLast()) {
            Device device = new Device();
            int id = cursor.getInt(cursor.getColumnIndex(SqliteHelper.Field_ID));
            int deviceId = cursor.getInt(cursor.getColumnIndex(SqliteHelper.Field_DEVICEID));
            String deviceName = cursor.getString(cursor.getColumnIndex(SqliteHelper.Field_DEVICENAME));
            String description = cursor.getString(cursor.getColumnIndex(SqliteHelper.Field_DESCRIPTION));
            String company = cursor.getString(cursor.getColumnIndex(SqliteHelper.Field_COMPANY));
            String ip = cursor.getString(cursor.getColumnIndex(SqliteHelper.Field_IP));
            byte[] status = cursor.getBlob(cursor.getColumnIndex(SqliteHelper.Field_STATUS));
            String template = cursor.getString(cursor.getColumnIndex(SqliteHelper.Field_TEMPLATENAME));
            device.setId(id);
            device.setRoomid(roomid);
            device.setDeviceId(deviceId);
            device.setDeviceName(deviceName);
            device.setDescription(description);
            device.setCompany(company);
            device.setType(type);
            device.setIp(ip);
            device.setTemplateName(template);
            device.setStatus(status);
            cursor.close();
            return device;
        }
        cursor.close();
        return null;
    }

    /**
     * 获得最大deviceid
     * @return
     */
    public int getMaxId() {
        Cursor cursor = db.rawQuery("select max(" + SqliteHelper.Field_ID + ")"
                + " from " + SqliteHelper.TB_DEVICE , null);
        cursor.moveToFirst();

        int id = -1;
        while (!cursor.isAfterLast()) {
            id = cursor.getInt(0);
            cursor.moveToNext();
        }
        cursor.close();
        return id;
    }

    /**
     * 获取设备对应的盒子信息
     * @param deviceId
     * @return
     */
    public int getControlForDevice(int deviceId) {
        int controlId = -1;
        Cursor cursor = db.rawQuery("select " + SqliteHelper.Field_DEVICEID
                + " from "
                + SqliteHelper.TB_DEVICE
                + " where " + SqliteHelper.Field_DEVICEID + "="
                + "(select " + SqliteHelper.Field_ID + " from " + SqliteHelper.TB_ROOM + " where " + SqliteHelper.Field_ROOMID + "="
                + "(select " + SqliteHelper.Field_ROOMID + " from " + SqliteHelper.TB_DEVICE + " where " + SqliteHelper.Field_DEVICEID + "="
                + deviceId + ")) and "+ SqliteHelper.Field_TYPE + "=" + MainActivity.TYPE_CONTROLLER
                , null);
        cursor.moveToFirst();

        while (!cursor.isAfterLast()) {
            controlId = cursor.getInt(0);
            cursor.moveToNext();
        }
        cursor.close();
        return controlId;
    }

    /**
     * 符合条件的数据库是否存在
     */
    public static boolean tableIsExist(String databaseFilename) {
        Cursor cursor = null;
        try {
            SQLiteDatabase database = SQLiteDatabase.openOrCreateDatabase(databaseFilename, null);
            String sql = String.format("select count(*) from sqlite_master where type='table' and name='" + SqliteHelper.TB_ROOM + "'");
            cursor = database.rawQuery(sql, null);
            if (cursor.moveToNext()) {
                int count = cursor.getInt(0);
                if (count > 0) {
                    cursor.close();
                    return true;
                } else {
                    cursor.close();
                    return false;
                }
            }
            cursor.close();
        }catch(Exception e){
            if(cursor!=null)
                cursor.close();
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 读取数据库文件（.sql），并执行sql语句
     */
    public boolean executeSQL(String sql) {
        boolean isSuccess = true;
        db.beginTransaction();
        try {
            String[] sqls = sql.split(";\n");
            for (int i=0; i<sqls.length-1; i++) {
                db.execSQL(sqls[i]);
            }
            db.setTransactionSuccessful();
        } catch (Exception e) {
            isSuccess = false;
        } finally {
            db.endTransaction(); //处理完成
            return isSuccess;
        }
    }



    public static void importDatabaseFile(Context context, String importPath) {
        File dir = new File(DB_DIR);
        if (!dir.exists()) {
            try {
                dir.mkdir();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        File dest = new File(dir, DB_NAME);
        if(dest.exists()){
            DataHelper.getInstance().close();
            dest.delete();
            dir.delete();
            File dir1 = new File(DB_DIR);
            dir1.mkdir();
            dest = new File(dir1, DB_NAME);
        }
        try {
            dest.createNewFile();
            File file = new File(importPath);
            if(!file.exists())
                return;
            FileInputStream in = new FileInputStream(file);
            int size = in.available();
            byte buf[] = new byte[size];
            in.read(buf);
            in.close();
            FileOutputStream out = new FileOutputStream(dest);
            out.write(buf);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try{
            DataHelper.getInstance().open();
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    public static boolean exportDatabaseFile(Context context, String exportPath, String exportName) {
        File dirSrc = new File(DB_DIR);
        File srcFile = new File(dirSrc, DB_NAME);
        if (!srcFile.exists() ) {
            return false;
        }
        File dirDest = new File(exportPath);
        if (!dirDest.exists()) dirDest.mkdir();

        File destFile = new File(dirDest, exportName);
        if (destFile.exists() ) {
            destFile.delete();
        }
        try {
            destFile.createNewFile();
            FileInputStream in = new FileInputStream(srcFile);
            int size = in.available();
            byte buf[] = new byte[size];
            in.read(buf);
            in.close();
            FileOutputStream out = new FileOutputStream(destFile);
            out.write(buf);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }
}
